/**
 * 用户管理-分组管理
 */
angular.module('inspinia').controller('userGroupCtrl',function(SweetAlert,i18nService,$scope,$http,$state,$stateParams,$compile,$filter,$log,$uibModal){
    i18nService.setCurrentLang('zh-cn');
    $scope.paginationOptions=angular.copy($scope.paginationOptions);

    $scope.status = [{text:"有效",value:1},{text:"无效",value:0}];

    $scope.deptList=angular.copy(initData.DEPT_LIST);
    $scope.deptList.unshift({value:"",text:"请选择"});

    $scope.info={groupName:"",id:"",byDeptId:""};
    $scope.submitting = false;
    $scope.saveStatus=0;//0保存1修改2详情


    //清空
    $scope.clear=function(){
        $scope.userGroup={id:"",groupName:"",byDeptId:""};
    };
    $scope.clear();

    $scope.changeDept = function() {
        if ($scope.info.byDeptId) {
            $scope.selectUserByDeptId($scope.info.byDeptId);
            //清空列表数据
            $scope.addUserData=[];
            rowList={};
        }
    }

    //查询用户列表
    $scope.selectUserByDeptId = function(byDeptId){
        $scope.userData=[];
        $http.get('user/selectUserByDeptId?deptId='+byDeptId).success(function(data){
            if(data!=null){
                $scope.userData = data;
            }
        });
    };

    $scope.userList = {
        data: 'userData',
        // enableHorizontalScrollbar: true,        //横向滚动条
        // enableVerticalScrollbar : true,  		//纵向滚动条
        columnDefs: [
            {field: 'id',displayName: '用户ID',width: 150, visible :false},
            {field: 'userName',displayName: '用户名',width: 150},
            {field: 'realName',displayName: '真实姓名',width:150},
            {field: 'status',displayName: '状态',width: 150,cellFilter:"formatDropping:"+angular.toJson($scope.status)},
            {field: 'deptId',displayName: '所属部门',width: 150, visible :false},
        ],
        onRegisterApi : function(gridApi) {
            $scope.gridApiGroup = gridApi;
            //全选
            $scope.gridApiGroup.selection.on.rowSelectionChangedBatch($scope,function (rows) {
                if(rows[0].isSelected){
                    $scope.testRow = rows[0].entity;
                    for(var i=0;i<rows.length;i++){
                        rowList[rows[i].entity.id]=rows[i].entity;
                    }
                    $scope.addList(rowList);
                }else{
                    rowList={};
                    for(var i=0;i<rows.length;i++){
                        $scope.delteData(rows[i].entity);
                    }
                }
            })
            //单选
            $scope.gridApiGroup.selection.on.rowSelectionChanged($scope,function (row) {
                if(row.isSelected){
                    rowList[row.entity.id]=row.entity;
                    $scope.addData(row.entity);
                }
                else{
                    delete rowList[row.entity.id];
                    $scope.delteData(row.entity);
                }
            })
        },
       isRowSelectable: function(row){ // 选中行
            if($scope.addUserData != null && $scope.addUserData.length>0){
                for(var i=0;i<$scope.addUserData.length;i++){
                    if(row.entity.id==$scope.addUserData[i].id){
                        row.grid.api.selection.selectRow(row.entity);
                    }
                }
            }
        }
    };


    $scope.addUserData=[];
    var rowList = [];
    $scope.addUserList = {
        data: 'addUserData',
        useExternalPagination: true,		    //开启拓展名
        enableHorizontalScrollbar: true,        //横向滚动条
        enableVerticalScrollbar : true,  		//纵向滚动条
        columnDefs : [                           //表格数据
            {field: 'id',displayName: '用户ID',width: 150, visible :false},
            {field: 'userName',displayName: '用户名',width: 150},
            {field: 'realName',displayName: '真实姓名',width:150},
            {field: 'status',displayName: '状态',width: 150,cellFilter:"formatDropping:"+angular.toJson($scope.status)},
            {field: 'deptId',displayName: '所属部门',width: 150, visible :false},
            {field: 'action',displayName: '操作',width:80,pinnedRight:true,cellTemplate:
                    '<a ng-show="grid.appScope.saveStatus!=2" class="lh30" ng-click="grid.appScope.delteData(row.entity)">移除</a> '}],
        onRegisterApi: function(gridApi) {
            $scope.addUserListGridApi = gridApi;
        },
    };

    $scope.addUserList2 = {
        data: 'addUserData',
        useExternalPagination: true,		    //开启拓展名
        enableHorizontalScrollbar: true,        //横向滚动条
        enableVerticalScrollbar : true,  		//纵向滚动条
        columnDefs : [                           //表格数据
            {field: 'id',displayName: '用户ID',width: 150, visible :false},
            {field: 'userName',displayName: '用户名',width: 150},
            {field: 'realName',displayName: '真实姓名',width:150},
            {field: 'status',displayName: '状态',width: 150,cellFilter:"formatDropping:"+angular.toJson($scope.status)},
            {field: 'deptId',displayName: '所属部门',width: 150, visible :false}],
        onRegisterApi: function(gridApi) {
            $scope.addUserListGridApi2 = gridApi;
        },
    };

    $scope.addList = function(rowList){
        if(rowList!=null){
            for(var i in rowList){
                if(rowList[i]!=null&&rowList[i]!=""){
                    if($scope.checkData($scope.addUserData,rowList[i],null)){
                        $scope.addUserData.push({
                            id:rowList[i].id,
                            userName:rowList[i].userName,
                            realName:rowList[i].realName,
                            status:rowList[i].status,
                            deptId:rowList[i].deptId,
                        });
                        //$scope.cancel();
                    }
                }
            }
        }
    };

    $scope.addData = function(row){
        if(row!=null&&row!=""){
            if($scope.checkData($scope.addUserData,row,null)){
                $scope.addUserData.push({
                    id:row.id,
                    userName:row.userName,
                    realName:row.realName,
                    status:row.status,
                    deptId:row.deptId
                });
               // $scope.cancel();
            }
        }
    };

    $scope.checkData = function(dataList,info,oldInfo){
        if(dataList!=null&&dataList.length>0){
            for(var i=0;i<dataList.length;i++){
                var item=dataList[i];
                if(oldInfo!=null){
                    if(item.id==oldInfo.id){
                        continue;
                    }
                }
                if(item.id==info.id){
                    return false;
                }
            }
        }
        return true;
    };

    $scope.delteData = function(row){
        if(row!=null&&row!=""){
            for(var j=0;j<$scope.addUserData.length;j++){
                var dateItem=$scope.addUserData[j];
                if(row.id==dateItem.id){
                    $scope.addUserData.splice(j, 1);
                }
            }
            for(var j=0;j<$scope.userData.length;j++){
                var dateItem=$scope.userData[j];
                if(row.id==dateItem.id){
                    $scope.gridApiGroup.selection.unSelectRow($scope.userData[j]);
                }
            }
        }
    };


    // 配置表格
    $scope.gridOptions={						//配置表格
        paginationPageSize:10,					//分页数量
        paginationPageSizes: [10,20,50,100],	//切换每页记录数
        useExternalPagination: true,		  //开启拓展名
        enableHorizontalScrollbar: 1,			//横向滚动条
        enableVerticalScrollbar : 1,			//纵向滚动条
        columnDefs:[							//表格数据
            { field: 'id',displayName:'ID',width:150},
            { field: 'byDeptId',displayName:'所属部门',width:300,cellFilter:"formatDropping:"+angular.toJson($scope.deptList)},
            { field: 'groupName',displayName:'分组名称',width:400},
            { field: 'createTime',displayName:'创建日期',width:400,cellFilter: 'date:"yyyy-MM-dd"'},
            { field: 'action',displayName:'操作',width:300,pinnedRight:true,editable:true,
                cellTemplate:
                '<a class="lh30" ng-show="grid.appScope.hasPermit(\'user.editUserGroup\')" ng-click="grid.appScope.userGroupEdit(row.entity.id)">编辑</a> ' +
                '<a class="lh30" ng-click="grid.appScope.detail(row.entity.id)">| 详情</a> ' +
                '<a class="lh30" ng-show="grid.appScope.hasPermit(\'user.deleteUserGroup\')" ng-click="grid.appScope.delete(row.entity.id)">| 删除</a> '
            }
        ],
        onRegisterApi: function(gridApi) {
            $scope.gridApi = gridApi;
            gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
                $scope.paginationOptions.pageNo = newPage;
                $scope.paginationOptions.pageSize = pageSize;
                $scope.query();
            });
        }
    };

    $scope.query = function () {
        $http({
            url: 'user/getUserGroupList?pageNo=' + $scope.paginationOptions.pageNo + "&pageSize=" + $scope.paginationOptions.pageSize,
            data: $scope.userGroup,
            method: 'POST'
        }).success(function (data) {
            if(data.status){
                $scope.gridOptions.data = data.page.result;
                $scope.gridOptions.totalItems = data.page.totalCount;
                console.log(data.page.result);
            }else{
                $scope.notice(data.msg);
            }
        }).error(function(){
        });
    };
    $scope.query();

	//提交
    $scope.commit = function(){

        if($scope.info.groupName==null||$scope.info.groupName==""){
            $scope.notice("分组名称不能为空!");
            return;
        }
        if($scope.info.groupName.length>15){
            $scope.notice("分组名称不能超过15字!");
            return;
        }

        if (!$scope.info.byDeptId) {
            $scope.notice("请选择所属部门");
            return;
        }

        var firstDeptId;
        var nextDeptId;

        if ($scope.addUserData.length == 0) {
            $scope.notice("请选择用户");
            return;
        }

        for(var i=0;i<$scope.addUserData.length;i++){
            var groupItem=$scope.addUserData[i];
            if(i==0){
                firstDeptId=groupItem.deptId;
            }else{
                nextDeptId=groupItem.deptId;
                if(firstDeptId!=nextDeptId){
                    $scope.notice("请选择同部门用户！");
                    return;
                }
            }
        }

        if ($scope.submitting == true) {
            return;
        }
        $scope.submitting = true;
        var data = {
            "info" : $scope.info,
            "addData" :$scope.addUserData
        };
        if($scope.saveStatus==0){
            $http.post("user/addUserGroup",angular.toJson(data))
                .success(function(data){
                    if(data.status){
                        $scope.notice(data.msg);
                        $scope.query();
                        $scope.cancel();
                    }else{
                        $scope.notice(data.msg);
                    }
                    $scope.submitting = false;
                })
                .error(function(){
                    $scope.submitting = false;
                });
        }else if($scope.saveStatus==1){
            $http.post("user/editUserGroup",angular.toJson(data))
                .success(function(data){
                    if(data.status){
                        $scope.notice(data.msg);
                        $scope.query();
                        $scope.cancel();
                    }else{
                        $scope.notice(data.msg);
                    }
                    $scope.submitting = false;
                })
                .error(function(){
                    $scope.submitting = false;
                });
        }

    }

	//取消
    $scope.submitCancel=function(){
        $scope.query();
    }
    $scope.submitCancel();

    $scope.isDetail=false;
    $scope.detail= function(id){
        $scope.isDetail=true;
        $scope.saveStatus=2;
        $http.post("user/getUserGroupById",angular.toJson(id)).success(function (data) {
            if(data.status){
                $scope.info = data.param;
                $scope.addUserData=data.list;
                $("#groupDetailModel").modal("show");
            }
        })
    }



	//修改配置
    $scope.userGroupEdit = function(id){
        $scope.isDetail=false;
        $scope.saveStatus=1;
        $http.post("user/getUserGroupById",angular.toJson(id)).success(function (data) {
            if(data.status){
                $scope.info = data.param;
                $scope.addUserData=data.list;
                $scope.userData=[];
                $scope.selectUserByDeptId($scope.info.byDeptId);
                $("#groupAddModel").modal("show");
                $scope.info.byDeptId = parseInt(data.param.byDeptId);
            }
        })
    }


	//添加
    $scope.groupAddModel = function(){
        $scope.info={groupName:"",id:"",byDeptId:""};

        $scope.addUserData=[];
        $scope.userData=[];
        $scope.isDetail=false;
        $scope.saveStatus=0;
        $("#groupAddModel").modal("show");
        $scope.gridApiGroup.selection.clearSelectedRows();
    }
    //返回
    $scope.cancel=function(){
        $scope.info={groupName:"",byDeptId:""};
        $('#groupAddModel').modal('hide');
        $("#groupDetailModel").modal("hide");
    }

    $scope.delete=function(id){
        //先查询是否有用户关联了该分组
        var userNames = '';
        $scope.baseInfo = {bossUserGroupId : id};
        $http.post('user/selectUserByCondition.do',"baseInfo="+angular.toJson($scope.baseInfo)+"&pageNo=1&pageSize=1000"
            ,{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
            .success(function(page){
                if(page){
                    if (page.result.length > 0) {
                        for (var i = 0; i < page.result.length; i++) {
                            userNames += page.result[i].userName + ',';
                        }
                        if (userNames) {
                            userNames = userNames.substring(0, userNames.length - 1);
                        }
                    }
                }
            }).error(function(){

            }).then(function () {
                var tips;
                if (userNames) {
                    tips= '用户 '+userNames+' 已关联该分组，是否继续删除？';
                } else {
                    tips = '确定删除该分组及分组下所有用户？';
                }

                SweetAlert.swal({
                        title: tips,
                        showCancelButton: true,
                        confirmButtonColor: "#DD6B55",
                        confirmButtonText: "确认",
                        cancelButtonText: "取消",
                        closeOnConfirm: true,
                        closeOnCancel: true },
                    function (isConfirm) {
                        if (isConfirm) {
                            $http.post("user/deleteUserGroupById",id)
                                .success(function(data){
                                    if(data.status){
                                        $scope.notice(data.msg);
                                        $scope.query();
                                    }else{
                                        $scope.notice(data.msg);
                                    }
                                })
                                .error(function(data){
                                    $scope.notice(data.msg);
                                });

                        }
                    });
            });

    };

});
